//
//  ZYLocationManager.m
//  YaYa
//
//  Created by 张亚 on 2019/1/11.
//  Copyright © 2019年 张亚. All rights reserved.
//

#import "ZYLocationManager.h"
#import <CoreLocation/CoreLocation.h>

@interface ZYLocationManager ()<CLLocationManagerDelegate>

@property (nonatomic, strong) CLLocationManager * locManager;

@property (nonatomic, copy) LocationManagerBlock block;

@end

@implementation ZYLocationManager

static ZYLocationManager * _instance = nil;
+ (instancetype)shareInstance {
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        _instance = [[self alloc] init];
    });
    return _instance;
}
- (instancetype)init {
    self = [super init];
    if (self) {
        
        _locManager = [[CLLocationManager alloc] init];
        [_locManager setDesiredAccuracy:kCLLocationAccuracyHundredMeters];
        _locManager.distanceFilter = 100;
        _locManager.delegate = self;
        
        if (![CLLocationManager locationServicesEnabled]) {
            NSLog(@"请开启定位服务");
        } else {
            CLAuthorizationStatus status = [CLLocationManager authorizationStatus];
            if (kCLAuthorizationStatusNotDetermined == status) {
                [_locManager requestWhenInUseAuthorization];
            }
        }
        
    }
    return self;
}

#pragma mark - CLLocationManagerDelegate
- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(nonnull NSArray<CLLocation *> *)locations {
    if (locations.count) {
        
        CLLocation * loc = locations.firstObject;
        CLLocationCoordinate2D coordinate = loc.coordinate;
        NSString * lat = [NSString stringWithFormat:@"%f",coordinate.latitude];
        NSString * lon = [NSString stringWithFormat:@"%f",coordinate.longitude];
        
        [ZYLocationManager shareInstance].lat = lat;
        [ZYLocationManager shareInstance].lon = lon;
        
        if (self.block) {
            self.block(lat, lon);
        }
        [self.locManager stopUpdatingLocation];
    }
}

#pragma mark - 代理回调
- (void)getLocation:(LocationManagerBlock)block {
    
    self.block = block;
    //开启定位
    [self.locManager startUpdatingLocation];
}

@end
